import CartCheckBox from "./CartCheckBox";
import EventEmitterUtils from "../../common/utils/EventEmitterUtils";
import HttpUtils from "../../common/utils/HttpUtils";
import CommonUtils from "../../common/utils/CommonUtils";
import urlHook from "../../common/utils/urlHook.js";
import StorageUtils from "../../common/utils/StorageUtils";
import ToastUtils from "../../common/utils/ToastUtils";
import Modal from "@ui/RJMart/modal";
import PopConfirm from "@ui/RJMart/popconfirm";
import Icon from "@ui/RJMart/icons";
import InfoModal from "@page/common/modal/InfoModal";
import ZenModal from "@root/components/ZenUI/ZenModal/ZenModal";
import Radio, { Group as RadioGroup } from "@ui/RJMart/radio";

export default class CartTableFooter extends React.Component {
    constructor() {
        super();
        this.state = {
            count: 0,
            totalPrice: 0,
            radioValue: 1
        };
    }

    componentDidMount() {
        // this.isFooterFixed()
        EventEmitterUtils.on("cartChoosedTotalCountChange", () => {
            this.calculatePrice();
        });
    }

    isFooterFixed() {
        const footerEle = document.querySelector(".cart-content-box-footer");
        if (footerEle) {
            let offsetTop = CommonUtils.getElementTop(footerEle);
            let clientHeight = screen.availHeight;

            if (offsetTop - 0 + 64 - clientHeight > 0) {
                this.setState({
                    isFixed: true
                });
            }
        }
    }

    //计算价格，数量
    calculatePrice() {
        //数量
        let eleList = document.querySelectorAll(".cart-pro-count-input-value");
        let count = 0;
        eleList &&
            eleList.forEach(ele => {
                count += ele.value - 0;
            });

        //价格
        let priceEleList = document.querySelectorAll(
            ".cart-pro-item-content-p7-choose"
        );
        let totalPrice = 0;
        priceEleList &&
            priceEleList.forEach(ele => {
                let price = ele.innerHTML.split("￥")[1] - 0;
                totalPrice += price;
            });

        this.setState({
            count,
            totalPrice
        });
    }

    componentWillUnmount() {
        EventEmitterUtils.off("cartChoosedTotalCountChange");
    }

    //关注商品
    interestProduct() {
        let productSns = this.getProductSns();
        if (productSns.length == 0) {
            alert("请选择商品");
            return;
        }

        HttpUtils.interestProduct(productSns)
            .then(res => {
                this.setState({
                    modalMsg: "关注商品成功"
                });
                setTimeout(() => {
                    this.infoModal.showModal();
                }, 100);
                EventEmitterUtils.emit("productSnsFocusOn", productSns);
            })
            .catch(err => {});
    }

    //删除购物车商品
    deleteShopCart() {
        let productSns = this.getProductSns();
        if (productSns.length == 0) {
            return;
        }

        if (!global.hasLogin) {
            this.deleteCartLocal(productSns);
            return;
        }

        HttpUtils.deleteShoppingCart(productSns)
            .then(res => {
                // alert('删除成功')
                this.emitEvents();
            })
            .catch(err => {});
    }

    emitEvents() {
        EventEmitterUtils.emit("refreshCartData", null);
        setTimeout(() => {
            EventEmitterUtils.emit("cartChoosedTotalCountChange", null);
        }, 1000);
    }

    deleteCartLocal(productSns) {
        StorageUtils.deleteCartCountByArr(productSns);
        this.emitEvents();
    }

    getProductSns() {
        const checkedEleList = document.querySelectorAll(
            ".cart-pro-item-content1"
        );
        let productSns = [];
        checkedEleList &&
            checkedEleList.forEach(ele => {
                let sn = ele.getAttribute("sn");
                productSns.push(sn);
            });
        return productSns;
    }

    getCartIds() {
        const checkedEleList = document.querySelectorAll(
            ".cart-pro-item-content1"
        );
        let cartIds = [];
        checkedEleList &&
            checkedEleList.forEach(ele => {
                let cartId = ele.getAttribute("cartid");
                cartIds.push(cartId);
            });
        return cartIds;
    }

    isProductEnough() {
        const eleList = document.querySelectorAll(
            ".cart-pro-item-content-sku-select"
        );

        if (eleList && eleList.length > 0) {
            return false;
        }
        return true;
    }

    goToBuy() {
        let _self = this;
        let productSns = this.getProductSns();
        if (productSns.length == 0) {
            this.setState({
                modalMsg: "请选择商品"
            });
            this.infoModal.showModal();
            return;
        }

        if (!this.isProductEnough()) {
            this.setState({
                modalMsg: "商品库存不够"
            });
            this.infoModal.showModal();
            return;
        }

        //判断是否中大
        //获取当前选中商品对象
        if (Uts.getCookie("orgId") == 3 || Uts.getCookie("orgId") == 37) {
            let selectCartList = [];
            let devideCategory = [700, 60, 61, 62, 63];
            let jidaCategory = [701, 66, 1563, 1571, 1578, 1584, 1593, 1610];//仅对暨大限制办公类1000元以上的商品下单
            //判断是否单价超出1000
            let isMatch = false;
            let totalPrice = 0;
            Uts.each(this.props.cartInfo, function(carItem, index) {
                Uts.each(carItem.cart, function(singleProduct, index2) {
                    if (Uts.contain(productSns, singleProduct.product.sn)) {
                        if(Uts.getCookie("orgId") == 37){
                            let hasCountProductSN={};
                            //如果是设备类型，即计算总额和判断单额是否超出
                            Uts.each(singleProduct.product.category, function(
                                item,
                                index
                            ) {
                                if (Uts.contain(jidaCategory, item.id)) {
                                    if (!hasCountProductSN[singleProduct.product.sn]) {
                                        totalPrice += Number(
                                            singleProduct.product.price *
                                            singleProduct.amount
                                        );
                                        hasCountProductSN[singleProduct.product.sn]=true;
                                    }

                                    if (singleProduct.product.price >= 1000) {
                                        isMatch = true;
                                    }
                                }
                            });
                        }
                        let hasCountProductSN={};
                        //如果是设备类型，即计算总额和判断单额是否超出
                        Uts.each(singleProduct.product.category, function(
                            item,
                            index
                        ) {
                            if (Uts.contain(devideCategory, item.id)) {
                                if (!hasCountProductSN[singleProduct.product.sn]) {
                                    totalPrice += Number(
                                        singleProduct.product.price *
                                        singleProduct.amount
                                    );
                                    hasCountProductSN[singleProduct.product.sn]=true;
                                }

                                if (singleProduct.product.price >= 1000) {
                                    isMatch = true;
                                }
                            }
                        });
                        selectCartList.push(singleProduct);
                    }
                });
            });

            if (
                isMatch ||
                (totalPrice >= 10000 && Uts.getCookie("orgId") != 37) ||
                (totalPrice >= 200000 && Uts.getCookie("orgId") == 37)
            ) {
                function closeModal(value) {
                    // console.log("run closeModal", value);
                    modal.remove();
                }

                function Content(props) {
                    return (
                        <div className="zen_fs-14">
                            <div className="zen_t-c zen_m-b-20 zen_m-t-30 zen_h-145">
                                {isMatch
                                    ? (Uts.getCookie("orgId") == 37 ? "采购仪器设备或办公用品单价不能超过1000元":"采购仪器设备单价不能超过1000元")
                                    : totalPrice >= 200000 &&
                                      Uts.getCookie("orgId") == 37
                                    ? "仪器设备单笔订单金额不能超过200000元"
                                    : "仪器设备单笔订单金额不能超过10000元"}
                            </div>
                            <div className="zen_ps-ab zen_b-40 zen_l-140">
                                <span
                                    className="zen_cur-p zen_p-h-40 zen_p-v-10 zen_bg-0093EB zen_bdr-4 zen_white "
                                    onClick={closeModal}
                                >
                                    知道了
                                </span>
                            </div>
                        </div>
                    );
                }
                let options = {
                    header: "提示",
                    modalClass: "zen_bdr-5 detail-zen-model",
                    // footer: "test footer",
                    content: Content,
                    size: "sm",
                    hideFooter: true,
                    // cbList: [closeModal],
                    close: closeModal
                };
                let modal = ZenModal.loadModal(options);
                modal.show();
                return false;
            }
        }

        //判断是否中大
        //有危险化学品，弹出提示
        if (Uts.getCookie("orgId") == 3) {
            const dangeEleList = document.querySelectorAll(
                ".cart-pro-item-content1 .cart-dange-tag"
            );
            let hasDange = false;
            if (dangeEleList && dangeEleList.length > 0) {
                hasDange = true;
            }

            let dangeAgree = localStorage.getItem("zhongdaDangeAgree");
            if (hasDange && !dangeAgree) {
                function closeModal(value) {
                    // console.log("run closeModal", value);
                    modal.remove();
                }

                function clickOk() {
                    localStorage.setItem("zhongdaDangeAgree", true);
                    closeModal();
                    _self.goToBuy();
                }

                function Content(props) {
                    props.item.passParams && props.item.passParams("abc");
                    return (
                        <div className="zen_fs-12 zen_646464">
                            {/*<p className="zen_l-h-50 zen_fs-16 zen_m-b-10" ></p>*/}
                            <p className="zen_l-h-22 zen_m-t-20 cart-text-indent">
                                本人将严格执行国家、地方有关实验危险品（包括危险化学品、菌（毒）种及其样本、危险气体等）的相关法规、标准以及学校、学院的相关管理制度，并承诺：
                            </p>
                            <br />
                            <p className="zen_l-h-22">
                                {" "}
                                1、已充分了解所购实验危险品的理化性质、储存要求、使用安全风险及相关应急措施；
                            </p>
                            <br />
                            <p className="zen_l-h-22">
                                2、购买的实验危险品仅用于教学或科研用途，并将严格按照实验室实验安全操作规程开展实验；
                            </p>
                            <br />
                            <p className="zen_l-h-22">
                                3、切实做好所购实验危险品的日常管理，按要求使用和存储，预防被盗、被窃、误食、误用等意外事故；
                            </p>
                            <br />
                            <p>4、严格按照学校相关规定规范处置相应实验废物。</p>
                            <br />
                            <div className="zen_m-t-25" />

                            <div className="zen_t-c zen_m-t-100">
                                <span
                                    className="zen_cur-p zen_p-h-40 zen_p-v-10 zen_bg-0093EB zen_bdr-4 zen_white"
                                    onClick={clickOk}
                                >
                                    同意
                                </span>
                            </div>
                        </div>
                    );
                }
                let options = {
                    header: "中山大学实验危险品安全承诺书",
                    modalClass: "zen_bdr-5 cart-zen-model",
                    // footer: "test footer",
                    content: Content,
                    size: "md",
                    hideFooter: true,
                    // cbList: [closeModal],
                    close: closeModal
                };
                let modal = ZenModal.loadModal(options);
                modal.show();
                return false;
            }
        }

        let cartIds = this.getCartIds();

        let cartIdsStr = cartIds.join(",");

        $state.go({
            stateName: "/statements",
            params: {
                ids: cartIdsStr
            }
        });
    }

    clickToOrder() {
        if (!global.hasLogin) {
            this.setState({
                modalMsg:
                    "请先登录，如果没有账号，请联系单位管理员或平台客服。",
                msgType: "toLogin"
            });
            this.infoModal.showModal();
            return;
        }
        this.goToBuy();
    }

    render() {
        const { all_selected, onClick } = this.props;
        const { count, totalPrice, modalMsg, msgType, isFixed } = this.state;
        return (
            <div
                className={
                    isFixed
                        ? "cart-content-box-footer cart-foote-fixed"
                        : "cart-content-box-footer"
                }
            >
                <CartCheckBox
                    selected={all_selected}
                    onClick={() => {
                        onClick();
                        setTimeout(() => {
                            EventEmitterUtils.emit(
                                "cartChoosedTotalCountChange",
                                null
                            );
                        }, 100);
                    }}
                />
                <p className={"cart-content-footer-p1"}>全选</p>
                {this.renderDelete()}
                {this.renderFcous()}
                <div className={"cart-content-footer-space"} />
                {this.renderTotalCount()}
                <div
                    onClick={() => {
                        if(global.isSupp){
                            return;
                        }
                        this.clickToOrder()
                    }}
                    className={global.isSupp? "cart-content-footer-buy-disable":"cart-content-footer-buy"}
                >
                    <p>生成采购申请单</p>
                </div>
                <InfoModal
                    content={modalMsg}
                    getRef={v => (this.infoModal = v)}
                    onConfrim={() => {
                        if (msgType == "toLogin") {
                            window.location.href = urlHook.login;
                        }
                    }}
                />
            </div>
        );
    }

    renderDelete() {
        let productSns = this.getProductSns();
        if (productSns.length == 0) {
            return (
                <p
                    onClick={() => {
                        this.setState({ modalMsg: "您未选择商品" });
                        this.infoModal.showModal();
                    }}
                    className={"cart-content-footer-p2"}
                >
                    批量删除
                </p>
            );
        }
        return (
            <PopConfirm
                content="确定批量删除吗?"
                position="topCenter"
                icon={
                    <Icon
                        type="exclamation-circle-fill"
                        size="small"
                        color="warning"
                    />
                }
                onConfirm={() => this.deleteShopCart()}
                onCancel={() => {
                    console.log("Cancel");
                }}
            >
                <p className={"cart-content-footer-p2"}>批量删除</p>
            </PopConfirm>
        );
    }

    renderFcous() {
        if (!global.hasLogin) {
            return null;
        }
        let productSns = this.getProductSns();
        if (productSns.length == 0) {
            return (
                <p
                    onClick={() => {
                        this.setState({ modalMsg: "您未选择商品" });
                        this.infoModal.showModal();
                    }}
                    className={"cart-content-footer-p3"}
                >
                    移入我的关注
                </p>
            );
        }
        return (
            <PopConfirm
                content="确定移入我的关注吗?"
                position="leftTop"
                icon={
                    <Icon
                        type="exclamation-circle-fill"
                        size="small"
                        color="warning"
                    />
                }
                onConfirm={() => this.interestProduct()}
                onCancel={() => {
                    console.log("Cancel");
                }}
            >
                <p className={"cart-content-footer-p3"}>移入我的关注</p>
            </PopConfirm>
        );
    }

    renderTotalCount() {
        const { count, totalPrice, modalMsg } = this.state;
        return (
            <div className={"cart-content-footer-i4"}>
                <div className={"cart-content-footer-total-price"}>
                    <div className={"cart-content-footer-total-price-item1"}>
                        <p className={"cart-content-footer-total-price-p"}>
                            已选择商品
                        </p>
                        <p className={"cart-content-footer-total-price-num"}>
                            {count}
                        </p>
                        <p className={"cart-content-footer-total-price-p"}>
                            件
                        </p>
                    </div>
                    <div className={"cart-content-footer-total-price-item2"}>
                        <p
                            className={
                                "cart-content-footer-total-price-item2-p"
                            }
                        >
                            总价：
                        </p>
                        <p
                            className={
                                "cart-content-footer-total-price-item2-p2"
                            }
                        >
                            {global.hasLogin? `¥${totalPrice.toFixed(2)}`:'0.00'}
                        </p>
                    </div>
                </div>
            </div>
        );
    }
}
